package com.common.upload;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.common.util.DateUtil;

public class FileUpload {
private Logger log = Logger.getLogger(this.getClass());
	public FileInfo upload(HttpServletRequest req,HttpServletResponse res,String saveFielPath){
		long startD = System.currentTimeMillis();
		FileInfo fileInfo = new FileInfo();
		String path = req.getContextPath();
		String savepath = req.getRealPath("")+ saveFielPath;
		System.out.println("savepath===="+savepath);
	try {
				   DiskFileItemFactory factory = new DiskFileItemFactory();
					// 设置内存缓冲区，超过后写入临时文件
					factory.setSizeThreshold(1024*1000);
					// 设置临时文件存储位置
					factory.setRepository(new File(savepath));
					ServletFileUpload upload = new ServletFileUpload(factory);
					// 设置单个文件的最大上传值
					upload.setFileSizeMax(1024L*1024*10*100);
					// 设置整个request的最大值
					upload.setSizeMax(1654262605);
					upload.setProgressListener(new FileUploadListener(req));
					
					//saveStatusBean(request, initStatusBean(request));		 
				        // process uploads ..
				    List fileItems = upload.parseRequest(req);
				   
				   Iterator i = fileItems.iterator();
				   FileItem uploadFileItem = null;
				   while (i.hasNext()) {
					    FileItem fi = (FileItem) i.next();
					    String fileName = fi.getName();
					    System.out.println("=====fileName=="+fileName);
					    String suffix = fileName.substring(fileName.lastIndexOf("\\")+1);
						String ext = fileName.substring(fileName.lastIndexOf('.')+1);
					    String saveFilename = DateUtil.formatNowDateTime("yyyyMMddHHmmssSSS")+ "." + ext;
					    fileInfo.setUploadName(suffix);
					    fileInfo.setSaveName(saveFilename);
					    System.out.println("=====suffix=="+suffix);
					    System.out.println("=====saveFilename=="+saveFilename);
					    if (saveFilename != null) {
						     File fullFile = new File(fi.getName());
						     File savedFile = new File(savepath, saveFilename);
						     fi.write(savedFile);
					    }
					    
					    fileInfo.setMsg("上传成功");
					    fileInfo.setStatus("1");
					    fileInfo.setFileUrl(req.getContextPath()+saveFielPath+"/"+fileInfo.getSaveName());
						//JSONObject jsonObject = JSONObject.fromObject(fileInfo);
						//System.out.println(jsonObject);
					    System.out.println("=====upload succeed");
					   }
				   	req.getSession().setAttribute("uploadInfo", new UploadInfo(-1, 0, 0,0,"done"));
				  } catch (Exception e) {
					  log.info(e.getMessage(),e);
				  	fileInfo.setErr("上传失败，文件大小不能超过10M！");
				  	fileInfo.setStatus("0");
					//JSONObject jsonObject = JSONObject.fromObject(fileInfo);
					//System.out.println(jsonObject);
					 System.out.println("=====upload error");
				  }
				 
				 long endD = System.currentTimeMillis();
				 System.out.println("上传时间======="+(endD-startD));
				 return fileInfo;
	}
}
